package com.example.demo.outlook.demo;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Random;


@Component
public class OssJavaSdkQuickStart {

    private static final String endPoint = "https://oss-cn-hangzhou.aliyuncs.com";

    private static final String region = "cn-hangzhou";

    private static final String bucketName = "linlsobject";

    private static final Integer maxIntNumber = 10000; //最大值范围为10000


    public static String generateUniqueBucketName(String prefix) {

        String timestamp = String.valueOf(System.currentTimeMillis());

        Random random = new Random();

        int randomNum = random.nextInt(maxIntNumber);

        return prefix + "-" + timestamp + "-" + randomNum;
    }


    public static OSS createClient() throws ClientException {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();

        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();


        Credentials credentials = new DefaultCredentials("LTAI5tFek1jmbBxW4EGv6GzP", "hC4PEttzsgPfjxumXFfvNCBJE9XoKT");

        DefaultCredentialProvider defaultCredentialProvider = new DefaultCredentialProvider("LTAI5tFek1jmbBxW4EGv6GzP", "hC4PEttzsgPfjxumXFfvNCBJE9XoKT");
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endPoint)
                .credentialsProvider(defaultCredentialProvider)
                .region(region)
                .build();

        return ossClient;
    }

    public static void fileUp(MultipartFile file) {

        OSS ossclient = null;
        try {

            System.out.println("111");
            ossclient = OssJavaSdkQuickStart.createClient();

           // String objectName = "exampledir/exampleobject.txt";
            String content = "Hello OSS";
            //ossclient.headObject()
            ossclient.putObject("linlsobject", file.getOriginalFilename(), new ByteArrayInputStream(file.getBytes()));
           // System.out.println("2. 文件 " + file + " 上传成功。");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossclient != null) {
                ossclient.shutdown();
            }
        }
        //OssJavaSdkQuickStart.createClient();

    }

    public static void fileDownload(String objectName) {

        OSS ossclient = null;
        try {
            ossclient = OssJavaSdkQuickStart.createClient();
            OSSObject ossObject = ossclient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. 下载的文件内容：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossclient != null) {
                ossclient.shutdown();
            }
        }

    }

    public static void fileUpload() throws ClientException {

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();

        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();


        Credentials credentials = new DefaultCredentials("LTAI5tFek1jmbBxW4EGv6GzP", "hC4PEttzsgPfjxumXFfvNCBJE9XoKT");

        DefaultCredentialProvider defaultCredentialProvider = new DefaultCredentialProvider("LTAI5tFek1jmbBxW4EGv6GzP", "hC4PEttzsgPfjxumXFfvNCBJE9XoKT");
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endPoint)
                .credentialsProvider(defaultCredentialProvider)
                .region(region)
                .build();

        try {
            // 1. 创建存储空间（Bucket）
            //ossClient.createBucket(bucketName);
            //System.out.println("1. Bucket " + bucketName + " 创建成功。");
            // 2. 上传文件
            String objectName = "exampledir/exampleobject.txt";
            String content = "Hello OSS";
            ossClient.putObject("linlsobject", objectName, new ByteArrayInputStream(content.getBytes()));
            System.out.println("2. 文件 " + objectName + " 上传成功。");
            // 3. 下载文件
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. 下载的文件内容：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. 列出文件
            System.out.println("4. 列出 Bucket 中的文件：");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
            // 5. 删除文件
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. 文件 " + objectName + " 删除成功。");
            // 6. 删除存储空间（Bucket）
           // ossClient.deleteBucket(bucketName);
            //System.out.println("6. Bucket " + bucketName + " 删除成功。");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (IOException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

}
